import axios from "axios";
import config from "./config";

// 自定义判断元素类型JS
function toType(obj) {
  return {}.toString
    .call(obj)
    .match(/\s([a-zA-Z]+)/)[1]
    .toLowerCase();
}
// 参数过滤函数
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key];
    }
    if (toType(o[key]) === "string") {
      o[key] = o[key].trim();
    } else if (toType(o[key]) === "object") {
      o[key] = filterNull(o[key]);
    } else if (toType(o[key]) === "array") {
      o[key] = filterNull(o[key]);
    }
  }
  return o;
}
/**
 *
 * @param {*} method 方法
 * @param {*} url url请求地址
 * @param {*} params 请求参数
 * @param {*} headers 请求头
 * @param {*} otherOptions 其他选项，会覆盖之前设置的
 */
function apiAxios(method, url, params, headers, otherOptions) {
  if (params) {
    params = filterNull(params);
  }
  let header = {
    "X-Requested-With": "XMLHttpRequest"
  };
  if (headers) {
    for (let key in headers) {
      header[key] = headers[key];
    }
  }
  console.log(config.baseUrl + url);
  const options = {
    method: method,
    url: url,
    data: method === "POST" || method === "PUT" ? params : null,
    params: method === "GET" || method === "DELETE" ? params : null,
    baseURL: config.baseUrl,
    withCredentials: true,
    headers: header
  };
  return new Promise((resolve, reject) => {
    axios(Object.assign(options, otherOptions))
      .then(function (res) {
        if (!res) {
          //服务器正常
          resolve({ code: 500, msg: "service can not reach!" });
          return;
        }
        if (res.status === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      })
      .catch(function (err) {
        reject(err);
      });
  });
}

export const get = (url, params) => apiAxios("GET", url, params);
export const post = (url, params) => apiAxios("POST", url, params);
export const put = (url, params) => apiAxios("PUT", url, params);
export const options = (url, params) => apiAxios("OPTIONS", url, params);
export const getFile = (url, params) =>
  apiAxios("GET", url, params, {
    responseType: "blob",
    'content-type': 'application/x-msdownload'
  });
